package com.javaweb.blogcite.controller.vo;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.javaweb.blogcite.pojo.Blog;
import com.javaweb.blogcite.pojo.BlogType;
import com.javaweb.blogcite.pojo.Toc;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class BlogItemView {
    private List<Toc> toc;
    private String title;
    private String description;
    private String thumb;
    private Long createDate;
    private Integer scanNumber;
    private Integer commentNumber;
    private Integer id;
    private BlogItemView.BlogTypeInner category;

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    class BlogTypeInner {
        Integer id;
        String name;
        Integer order;
        Integer articleCount;
    }

    public BlogItemView(Blog blog, BlogType category) {
        this.id = blog.getId();
        this.createDate = blog.getCreateDate();
        this.scanNumber = blog.getScanNumber();
        this.commentNumber = blog.getCommentNumber();
        this.title = blog.getTitle();
        this.description = blog.getDescription();
        this.thumb = blog.getThumb();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 将 toc json 字符串转化成 Toc 对象
            this.toc = objectMapper.readValue(blog.getToc(), new TypeReference<List<Toc>>() {});
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        if (category != null) {
            this.category = new BlogItemView.BlogTypeInner(category.getId(), category.getName(), category.getOrder(), category.getBlogCount());
        } else {
            this.category = null;
        }
    }
}
